'use client';

import { VideoType } from '@/lib/video/video-service';
import HtmlLink from '@/app/components/common/html-link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import React from 'react';
import { dynamicWidth } from '@/lib/utils/utils';

interface NavBarProps {
  types: VideoType[];
}

export default function NavBar({ types }: NavBarProps) {
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchActive, setIsSearchActive] = useState(false);
  const [showAllMenuItems, setShowAllMenuItems] = useState(false);
  const [visibleMenuItems, setVisibleMenuItems] = useState<number>(types.length);
  const [activeSubMenu, setActiveSubMenu] = useState<number | null>(null);
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
  const [isSubMenuHovered, setIsSubMenuHovered] = useState(false);
  const [closeSubMenuTimeout, setCloseSubMenuTimeout] = useState<NodeJS.Timeout | null>(null);
  const [activeMoreSubmenu, setActiveMoreSubmenu] = useState<number | null>(null);
  const [isMoreSubmenuHovered, setIsMoreSubmenuHovered] = useState(false);
  const [closeMoreSubmenuTimeout, setCloseMoreSubmenuTimeout] = useState<NodeJS.Timeout | null>(null);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const navMenuRef = useRef<HTMLDivElement>(null);
  const navContainerRef = useRef<HTMLDivElement>(null);
  const menuItemsRef = useRef<Array<HTMLLIElement | null>>([]);
  const menuRefs = useRef<Map<number, DOMRect>>(new Map());
  const submenuRefs = useRef<Record<number, HTMLDivElement | null>>({});
  const moreButtonRef = useRef<HTMLLIElement | null>(null);
  const moreMenuRef = useRef<HTMLDivElement | null>(null);
  const moreSubmenuRefs = useRef<Record<number, HTMLDivElement | null>>({});
  const [closeMoreMenuTimeout, setCloseMoreMenuTimeout] = useState<NodeJS.Timeout | null>(null);
  const [isMoreMenuHovered, setIsMoreMenuHovered] = useState(false);
  const [, setDetailPageCategoryId] = useState<number | null>(null);
  const [detailPageActualTypeId, setDetailPageActualTypeId] = useState<number | null>(null);
  const [selectedTypeIds, setSelectedTypeIds] = useState<number[]>([]);

  // 过滤出父分类
  const parentTypes = types.filter(type => !type.parentId);

  // 判断是否在首页
  const isHomePage = pathname === '/';
  
  // 初始化Portal容器
  useEffect(() => {
    setPortalContainer(document.body);
  }, []);
  
  // 获取URL中的type参数
  useEffect(() => {
    // 如果是类型筛选页(/type/*)，检查URL中是否有type参数
    if (pathname.startsWith('/type/')) {
      // 使用useSearchParams获取type参数（会自动响应URL变化）
      const typeParams = searchParams.getAll('type');
      
      if (typeParams.length > 0) {
        // 转换为数字数组
        const typeIds = typeParams.map(id => parseInt(id, 10)).filter(id => !isNaN(id));
        setSelectedTypeIds(typeIds);
      } else {
        setSelectedTypeIds([]);
      }
    } else if (pathname.startsWith('/detail/')) {
      // 详情页特殊处理 - 如果有实际分类ID，将其添加到selectedTypeIds中
      if (detailPageActualTypeId) {
        setSelectedTypeIds([detailPageActualTypeId]);
      } else {
        setSelectedTypeIds([]);
      }
    } else {
      setSelectedTypeIds([]);
    }
    
    // 调试输出
    console.log('URL参数已更新:', Array.from(searchParams.entries()));
  }, [pathname, searchParams, detailPageActualTypeId]);
  
  // 当在详情页时，读取分类ID
  useEffect(() => {
    if (pathname.startsWith('/detail/')) {
      const container = document.querySelector('[data-top-category-id]');
      if (container) {
        const categoryId = container.getAttribute('data-top-category-id');
        if (categoryId) {
          setDetailPageCategoryId(parseInt(categoryId, 10));
        }
        
        // 读取实际分类ID
        const actualTypeId = container.getAttribute('data-actual-type-id');
        if (actualTypeId) {
          const typeId = parseInt(actualTypeId, 10);
          setDetailPageActualTypeId(typeId);
          // 在详情页设置selectedTypeIds，确保二级菜单项高亮
          setSelectedTypeIds([typeId]);
        } else {
          setDetailPageActualTypeId(null);
        }
      }
    } else {
      setDetailPageCategoryId(null);
      setDetailPageActualTypeId(null);
    }
  }, [pathname]);

  // 计算可见菜单项数量
  useEffect(() => {
    const calculateVisibleItems = () => {
      const container = navContainerRef.current;
      if (!container) return;

      const containerWidth = Number(container.offsetWidth);

      let totalWidth = 0;
      let visibleCount = 0;

      // 保留40px作为更多按钮的宽度，使用动态计算
      const reservedWidth = dynamicWidth(52);

      for (let i = 0; i < menuItemsRef.current.length; i++) {
        const item = menuItemsRef.current[i];
        if (!item) continue;

        totalWidth += Number(item.offsetWidth) + (i > 0 ? dynamicWidth(4) : 0);

        // 如果加上这个项目后总宽度超过容器宽度减去保留宽度，则停止计算
        if ((totalWidth + reservedWidth) > containerWidth) {
          break;
        }

        visibleCount = i + 1;
      }
      setVisibleMenuItems(Math.max(2, visibleCount)); // 至少保留2个菜单项
    };

    calculateVisibleItems();
    window.addEventListener('resize', calculateVisibleItems);

    return () => window.removeEventListener('resize', calculateVisibleItems);
  }, [parentTypes]);

  // 更新子菜单位置
  useEffect(() => {
    const updateSubmenuPositions = () => {
      // 获取每个菜单项的位置
      menuItemsRef.current.forEach((item, index) => {
        if (index === 0) return; // 跳过首页菜单项

        if (!item) return;

        const typeId = parentTypes[index - 1]?.id;
        if (!typeId) return;

        const rect = item.getBoundingClientRect();
        menuRefs.current.set(typeId, rect);

        const submenu = submenuRefs.current[typeId];
        if (!submenu) return;

        submenu.style.left = `${rect.left}px`;
      });
    };

    updateSubmenuPositions();
    window.addEventListener('resize', updateSubmenuPositions);
    window.addEventListener('scroll', updateSubmenuPositions);

    return () => {
      window.removeEventListener('resize', updateSubmenuPositions);
      window.removeEventListener('scroll', updateSubmenuPositions);
    };
  }, [parentTypes, visibleMenuItems]);

  // 处理搜索提交
  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchQuery.trim()) {
      router.push(`/search?keyword=${encodeURIComponent(searchQuery.trim())}`);
      setIsSearchActive(false);
    }
  };

  // 鼠标进入时显示子菜单
  const handleMouseEnter = (id: number) => {
    if (closeSubMenuTimeout) {
      clearTimeout(closeSubMenuTimeout);
      setCloseSubMenuTimeout(null);
    }
    setActiveSubMenu(id);
  };

  // 鼠标离开菜单项时不立即隐藏子菜单，而是设置延迟
  const handleMouseLeave = () => {
    const timeout = setTimeout(() => {
      if (!isSubMenuHovered) {
        setActiveSubMenu(null);
      }
    }, 300);
    setCloseSubMenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 处理鼠标进入子菜单
  const handleSubMenuMouseEnter = () => {
    setIsSubMenuHovered(true);
    if (closeSubMenuTimeout) {
      clearTimeout(closeSubMenuTimeout);
      setCloseSubMenuTimeout(null);
    }
  };

  // 处理鼠标离开子菜单
  const handleSubMenuMouseLeave = () => {
    setIsSubMenuHovered(false);
    const timeout = setTimeout(() => {
      if (!isSubMenuHovered) {
        setActiveSubMenu(null);
      }
    }, 300);
    setCloseSubMenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 处理点击更多按钮
  const handleMoreButtonClick = () => {
    setShowAllMenuItems(!showAllMenuItems);
    // 点击更多按钮时，关闭所有二级菜单
    setActiveSubMenu(null);
    setIsSubMenuHovered(false);
  };

  // 处理鼠标进入更多菜单
  const handleMoreMenuMouseEnter = () => {
    setIsMoreMenuHovered(true);
    if (closeMoreMenuTimeout) {
      clearTimeout(closeMoreMenuTimeout);
      setCloseMoreMenuTimeout(null);
    }
    // 进入更多菜单时关闭主导航菜单的子菜单
    setActiveSubMenu(null);
  };

  // 处理鼠标离开更多菜单
  const handleMoreMenuMouseLeave = () => {
    setIsMoreMenuHovered(false);
    const timeout = setTimeout(() => {
      if (!isMoreMenuHovered) {
        setShowAllMenuItems(false);
      }
    }, 300);
    setCloseMoreMenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 处理鼠标进入更多按钮
  const handleMoreButtonMouseEnter = () => {
    if (closeMoreMenuTimeout) {
      clearTimeout(closeMoreMenuTimeout);
      setCloseMoreMenuTimeout(null);
    }
    // 立即显示菜单
    setShowAllMenuItems(true);
    // 隐藏主导航菜单的二级菜单
    setActiveSubMenu(null);
  };

  // 处理鼠标离开更多按钮
  const handleMoreButtonMouseLeave = () => {
    const timeout = setTimeout(() => {
      if (!isMoreMenuHovered) {
        setShowAllMenuItems(false);
      }
    }, 300);
    setCloseMoreMenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 处理鼠标进入更多菜单项
  const handleMoreMenuItemMouseEnter = (id: number) => {
    if (closeMoreSubmenuTimeout) {
      clearTimeout(closeMoreSubmenuTimeout);
      setCloseMoreSubmenuTimeout(null);
    }
    setActiveMoreSubmenu(id);
  };

  // 处理鼠标离开更多菜单项
  const handleMoreMenuItemMouseLeave = () => {
    // 不立即关闭，延迟处理，给用户时间移动到二级菜单
    const timeout = setTimeout(() => {
      // 只有当鼠标不在二级子菜单上时才清除
      if (!isMoreSubmenuHovered) {
        setActiveMoreSubmenu(null);
      }
    }, 300);
    setCloseMoreSubmenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 处理鼠标进入更多子菜单
  const handleMoreSubmenuMouseEnter = (id: number) => {
    setIsMoreSubmenuHovered(true);
    if (closeMoreSubmenuTimeout) {
      clearTimeout(closeMoreSubmenuTimeout);
      setCloseMoreSubmenuTimeout(null);
    }
    if (activeMoreSubmenu !== id) {
      setActiveMoreSubmenu(id);
    }
  };

  // 处理鼠标离开更多子菜单
  const handleMoreSubmenuMouseLeave = () => {
    setIsMoreSubmenuHovered(false);
    const timeout = setTimeout(() => {
      if (!isMoreSubmenuHovered) {
        setActiveMoreSubmenu(null);
      }
    }, 350);
    setCloseMoreSubmenuTimeout(timeout as unknown as NodeJS.Timeout);
  };

  // 清理超时
  useEffect(() => {
    return () => {
      if (closeMoreMenuTimeout) {
        clearTimeout(closeMoreMenuTimeout);
      }
      if (closeSubMenuTimeout) {
        clearTimeout(closeSubMenuTimeout);
      }
      if (closeMoreSubmenuTimeout) {
        clearTimeout(closeMoreSubmenuTimeout);
      }
    };
  }, [closeMoreMenuTimeout, closeSubMenuTimeout, closeMoreSubmenuTimeout]);

  // 点击document时关闭所有菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      // 关闭二级菜单
      const isClickInSubMenu = Object.values(submenuRefs.current).some(
        ref => ref && ref.contains(event.target as Node)
      );
      
      const isClickInMenu = menuItemsRef.current.some(
        ref => ref && ref.contains(event.target as Node)
      );
      
      if (!isClickInSubMenu && !isClickInMenu) {
        setActiveSubMenu(null);
      }

      // 关闭更多菜单
      if (
        showAllMenuItems && 
        moreButtonRef.current && 
        !moreButtonRef.current.contains(event.target as Node) &&
        moreMenuRef.current &&
        !moreMenuRef.current.contains(event.target as Node)
      ) {
        setShowAllMenuItems(false);
        setActiveMoreSubmenu(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showAllMenuItems]);
  
  // 全局鼠标移动事件，检测是否移出导航区域
  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      // 如果有活跃的子菜单，检查鼠标是否移出导航区域
      if (activeSubMenu !== null) {
        const navElement = navContainerRef.current;
        const activeSubMenuElement = submenuRefs.current[activeSubMenu];
        
        if (navElement && activeSubMenuElement) {
          const navRect = navElement.getBoundingClientRect();
          const subMenuRect = activeSubMenuElement.getBoundingClientRect();
          
          // 检查鼠标是否在导航区域或子菜单区域内
          const isInNavArea = 
            e.clientX >= navRect.left && 
            e.clientX <= navRect.right && 
            e.clientY >= navRect.top && 
            e.clientY <= navRect.bottom + 20; // 添加一点缓冲区
            
          const isInSubMenuArea = 
            e.clientX >= subMenuRect.left && 
            e.clientX <= subMenuRect.right && 
            e.clientY >= subMenuRect.top && 
            e.clientY <= subMenuRect.bottom;
            
          // 如果鼠标不在任何区域内，关闭子菜单
          if (!isInNavArea && !isInSubMenuArea && !isSubMenuHovered) {
            setActiveSubMenu(null);
          }
        }
      }
    };
    
    document.addEventListener('mousemove', handleMouseMove);
    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
    };
  }, [activeSubMenu, isSubMenuHovered]);

  return (
    <>
      <header className={`${pathname.startsWith("/detail/") ? 'max-sm:hidden' : ''} h-14 sm:h-16 fixed top-0 left-0 right-0 z-50 transition-all duration-300 bg-black/90 shadow-lg backdrop-blur-sm`}>
        {/* 顶部导航 */}
        <div className="container mx-auto px-3 sm:px-6 md:px-8 lg:px-12 xl:px-20 2xl:px-24 max-w-full overflow-x-hidden">
          <div className="flex items-center justify-between py-2 sm:py-3">
            {/* Logo */}
            <HtmlLink href="/" className={`flex items-center ${isSearchActive ? 'md:flex hidden' : 'flex'}`}>
              <span className="text-app-xl font-bold text-red-600">YZZY</span>
              <span className="ml-1 sm:ml-2 text-lg text-gray-300 text-nowrap">影视资源</span>
            </HtmlLink>

            {/* 桌面端导航 */}
            <div
              ref={navContainerRef}
              className={`hidden md:flex overflow-hidden items-center flex-1 mx-8 ${isSearchActive ? 'hidden' : ''}`}
            >
              <nav className={`w-full relative`}>
                <ul className={`flex items-center space-x-1 text-nowrap relative overflow-hidden`}>
                  <li
                    ref={el => { menuItemsRef.current[0] = el; }}
                    className="relative group"
                  >
                    <HtmlLink href="/" className={`px-3 text-nowrap block py-2 hover:text-red-500 transition text-gray-400`}>
                      首页
                    </HtmlLink>
                  </li>

                  {parentTypes.map((type, index) => {
                    // 获取当前分类的子分类
                    const subTypes = types.filter((subType) => subType.parentId === type.id);
                    const hasSubTypes = subTypes.length > 0;
                    const isOverflow = index + 1 >= visibleMenuItems
                    return (
                      <React.Fragment key={type.id}>
                        <li
                          ref={el => { menuItemsRef.current[index + 1] = el; }}
                          className={`${isOverflow ? "invisible" : ""} relative`}
                          onMouseEnter={() => hasSubTypes && handleMouseEnter(type.id)}
                          onMouseLeave={hasSubTypes ? handleMouseLeave : undefined}
                        >
                          <HtmlLink
                            href={`/type/${type.id}`}
                            className={`px-3 py-2 transition-colors duration-200 hover:text-red-500 rounded-md flex items-center text-gray-400 font-medium`}
                          >
                            <span>{type.name}</span>
                            {hasSubTypes && (
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-4 w-4 ml-1"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M19 9l-7 7-7-7"
                                />
                              </svg>
                            )}
                          </HtmlLink>

                          {/* 子菜单 - 只在有子分类时渲染DOM元素 */}
                          {hasSubTypes && (
                            <div
                              ref={el => { submenuRefs.current[type.id] = el; }}
                              className={`fixed top-[60px] z-[100] w-40 bg-background-dark rounded shadow-lg transition-all duration-300 translate-x-0 ${
                                // 只在鼠标悬停时才显示菜单
                                activeSubMenu === type.id ? "opacity-100 visible" : "opacity-0 invisible pointer-events-none"
                              }`}
                              onMouseEnter={handleSubMenuMouseEnter}
                              onMouseLeave={handleSubMenuMouseLeave}
                            >
                              <ul className="py-2">
                                {subTypes.map((subType) => {
                                  return (
                                    <li key={subType.id} className={`transition-colors duration-150 hover:bg-background-card`}>
                                      <HtmlLink
                                        href={
                                          `/type/${type.id}.html?type=${subType.id}`
                                        }
                                        className={`block px-4 py-2 hover:text-red-500 transition-colors duration-150 text-gray-400`}
                                        
                                      >
                                        {subType.name}
                                      </HtmlLink>
                                    </li>
                                  );
                                })}
                              </ul>
                            </div>
                          )}
                        </li>
                        {/* 更多菜单项按钮 - 只显示图标 */}
                        {visibleMenuItems < parentTypes.length + 1 && index+2 === visibleMenuItems && (
                          <li
                            ref={moreButtonRef}
                            className="group relative -left-4 bg-black px-2"
                            onMouseEnter={handleMoreButtonMouseEnter}
                            onMouseLeave={handleMoreButtonMouseLeave}
                          >
                            <button
                              onClick={handleMoreButtonClick}
                              className="p-2 rounded-full hover:bg-background-card hover:text-red-500 transition-all duration-200 text-gray-300 focus:outline-none"
                              aria-label={showAllMenuItems ? '收起菜单' : '显示更多菜单'}
                            >
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className={`h-5 w-5 transition-transform duration-200 ${showAllMenuItems ? 'rotate-180' : ''}`}
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M19 9l-7 7-7-7"
                                />
                              </svg>
                            </button>
                          </li>
                        )}
                      </React.Fragment>
                    );
                  })}
                </ul>
              </nav>
            </div>

            {/* 搜索图标 */}
            <button
              onClick={() => setIsSearchActive(true)}
              className="p-2 ml-auto text-white focus:outline-none md:hidden"
              aria-label="打开搜索"
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-6 w-6"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                />
              </svg>
            </button>

            {/* 搜索框 - 移动到最右侧 */}
            <div className={`relative ${isSearchActive ? 'flex-1 md:block' : 'hidden md:block ml-auto'}`}>
              <form onSubmit={handleSearchSubmit} className="flex items-center">
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="搜索影片..."
                  className="py-1.5 px-4 pr-10 bg-background-card text-white rounded-lg border border-gray-700 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent w-full md:w-56 transition-all duration-300 placeholder-gray-400"
                />
                <button
                  type="submit"
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white transition-colors duration-200"
                  aria-label="搜索"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className="h-5 w-5"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                    />
                  </svg>
                </button>
              </form>
            </div>

            {/* 取消搜索（移动端） */}
            {isSearchActive && (
              <button
                onClick={() => setIsSearchActive(false)}
                className="p-2 ml-2 text-white focus:outline-none md:hidden"
                aria-label="取消搜索"
              >
                取消
              </button>
            )}
          </div>
        </div>

        {/* 移动端分类导航 - 横向滚动 */}
        {isHomePage && !isSearchActive && (
          <div
            ref={navMenuRef}
            className="overflow-x-auto no-scrollbar bg-background-dark/80 backdrop-blur-sm md:hidden"
          >
            <div className="flex whitespace-nowrap px-4 py-3 space-x-6">
              <HtmlLink
                key="home" 
                href="/"
                className={`text-base ${pathname === '/' ? 'text-red-500' : 'text-gray-300'}`}
              >
                首页
              </HtmlLink>

              {parentTypes.map((type, index) => (
                <HtmlLink
                  key={type.id}
                  href={`/type/${type.id}`}
                  className={`text-base ${pathname === `/type/${type.id}` || pathname.startsWith(`/type/${type.id}/`) ? 'text-red-500' : 'text-gray-300'} ${index === parentTypes.length - 1 ? 'pr-6' : ''}`}
                >
                  {type.name}
                </HtmlLink>
              ))}
            </div>
          </div>
        )}

        {/* 使用Portal渲染子菜单 */}
        {showAllMenuItems && moreButtonRef.current && portalContainer && (
          createPortal(
            <div
              ref={moreMenuRef}
              className="fixed z-[100] w-48 bg-background-dark rounded shadow-lg transition-all duration-200"
              style={{
                top: moreButtonRef.current.getBoundingClientRect().bottom + 'px',
                right: (window.innerWidth - moreButtonRef.current.getBoundingClientRect().right) + 'px',
              }}
              onMouseEnter={handleMoreMenuMouseEnter}
              onMouseLeave={handleMoreMenuMouseLeave}
            >
              <ul className="py-2">
                {parentTypes.map((type, index) => {
                  // 只显示溢出的菜单项
                  if (index < visibleMenuItems - 1) return null;

                  // 获取当前分类的子分类
                  const subTypes = types.filter((subType) => subType.parentId === type.id);
                  const hasSubTypes = subTypes.length > 0;
                  const isSubmenuActive = activeMoreSubmenu === type.id;

                  return (
                    <li 
                      key={type.id} 
                      className={`relative`}
                      onMouseEnter={() => hasSubTypes && handleMoreMenuItemMouseEnter(type.id)}
                      onMouseLeave={hasSubTypes ? handleMoreMenuItemMouseLeave : undefined}
                    >
                      <div className={`flex items-center justify-between transition-colors duration-150 ${isSubmenuActive ? 'bg-background-card' : 'hover:bg-background-card'}`}>
                        <HtmlLink
                          href={`/type/${type.id}`}
                          className={`block px-4 py-2 hover:text-red-500 transition-colors duration-150 flex-grow`}
                          onClick={(e) => {
                            e.preventDefault();
                            
                            // 直接前往主分类页，不带type参数
                            const url = `/type/${type.id}.html`;
                            
                            // 直接清空所有选中项，因为是前往主分类页
                            setSelectedTypeIds([]);
                            
                            // 关闭菜单
                            setActiveMoreSubmenu(null);
                            setShowAllMenuItems(false);
                            
                            // 使用Next.js的router.push进行客户端导航
                            router.push(url);
                          }}
                        >
                          {type.name}
                        </HtmlLink>
                        {hasSubTypes && (
                          <div className="px-3 py-2 text-gray-400">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              className="h-4 w-4"
                              fill="none"
                              viewBox="0 0 24 24"
                              stroke="currentColor"
                            >
                              <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                strokeWidth={2}
                                d="M9 5l7 7-7 7"
                              />
                            </svg>
                          </div>
                        )}
                      </div>

                      {/* 二级子菜单 */}
                      {hasSubTypes && (
                        <div
                          ref={el => { moreSubmenuRefs.current[type.id] = el; }}
                          className={`absolute left-[calc(100%-10px)] top-0 w-48 bg-gray-900 rounded shadow-lg transition-opacity duration-300 -mt-2 pl-0 ${
                            // 只在鼠标悬停时显示菜单
                            isSubmenuActive ? 'opacity-100 visible pointer-events-auto' : 'opacity-0 invisible pointer-events-none'
                          }`}
                          style={{ minHeight: '100%' }}
                          onMouseEnter={() => handleMoreSubmenuMouseEnter(type.id)}
                          onMouseLeave={handleMoreSubmenuMouseLeave}
                        >
                          {/* 增加一个透明的桥接区域，捕获鼠标移动 */}
                          <div className="absolute -left-10 top-0 w-10 h-full bg-transparent"></div>
                          <ul className="py-2">
                            {subTypes.map((subType) => (
                              <li key={subType.id} className={`transition-colors duration-150 hover:bg-background-card`}>
                                <HtmlLink
                                  href={
                                    selectedTypeIds.includes(subType.id)
                                      ? `/type/${type.id}.html`
                                      : `/type/${type.id}.html?type=${subType.id}`
                                  }
                                  className={`block px-4 py-2 hover:text-red-500 transition-colors duration-150 text-gray-400`}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    
                                    // 首先直接修改URL，不使用router.push
                                    // 只保留顶级分类和二级分类参数，去掉其他参数
                                    const url = selectedTypeIds.includes(subType.id)
                                      ? `/type/${type.id}.html` // 如果已经选中，只保留顶级分类
                                      : `/type/${type.id}.html?type=${subType.id}`; // 只保留顶级分类和二级分类参数
                                    
                                    // 始终只保留当前点击的项
                                    setSelectedTypeIds([subType.id]);
                                    
                                    // 关闭菜单
                                    setActiveMoreSubmenu(null);
                                    setShowAllMenuItems(false);
                                    
                                    // 使用Next.js的router.push进行客户端导航
                                    router.push(url);
                                  }}
                                >
                                  {subType.name}
                                </HtmlLink>
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}
                    </li>
                  );
                })}
              </ul>
            </div>,
            portalContainer
          )
        )}
      </header>
      <div className={`${pathname.startsWith("/detail/") ? 'max-sm:hidden' : ''}  h-14 sm:h-16`}></div>
    </>
  );
} 